#!/usr/bin/python
import sys,re,datetime,time,common.db,logging

def dmz_minute(type,datetime1,datetime2):
    if type=='create_role':
        field='count(*)'
        table='create_role'
        condition=''
        monitor_type=1
    elif type=='wedding':
        field='count(*)'
        table='wedding'
        condition=''
        monitor_type=2
    elif type=='login':
        field='count(*)'
        table='login'
        condition=''
        monitor_type=3
    elif type=='consume':
        field='sum(MoneyOld-MoneyNew)'
        table='money'
        condition='and MoneyOld>MoneyNew'
        monitor_type=4
    elif type=='recharge':
        field='sum(MoneyNew-MoneyOld)'
        table='money'
        condition="and MoneyNew>MoneyOld and TransID like '%TP28%'"
        monitor_type=6
    else:
        return False

    conn_web = common.db.connect('DMZwebDB')
    conn_bill = common.db.connect('billDB')
    cursor_web = conn_web.cursor()
    cursor_bill = conn_bill.cursor()
    
    hour1=datetime1.strftime('%Y-%m-%d %H')
    hour2=datetime2.strftime('%Y-%m-%d %H')
    delete_sql = """delete from dmz_gm.monitordata 
    where StatTime between '%s:00:00' and '%s:59:59' and MonitorType =%d"""%(hour1,hour2,monitor_type)
    try:
        delete_rows=cursor_web.execute(delete_sql)
    except Exception,data:
        logging.log(logging.ERROR,type+' '+data)
        sys.exit(0)
    if delete_rows>0:
        logging.log(logging.INFO,type+' delete_rows: '+str(delete_rows))
    
    one_day=datetime.timedelta(days=1)
    dt=datetime1.replace(hour=0,minute=0,second=0,microsecond=0)
    while dt<=datetime2:
        date_number = dt.strftime('%Y%m%d')

        select_sql = """select ZoneID,date_format(BillTime,'%%Y-%%m-%%d %%H:%%i') minute,%s
        from dmz_bill_%s.%s 
        where BillTime BETWEEN '%s:00:00' AND '%s:59:59' %s 
        group by ZoneID,minute""" % (field,date_number,table,hour1,hour2,condition)
        try:
            select_rows=cursor_bill.execute(select_sql)
        except Exception,data:
            logging.log(logging.ERROR,type+' '+data)
            sys.exit(0)
        logging.log(logging.INFO,type+' select_rows: '+str(select_rows))
        if select_rows<=0:
            return

        row = cursor_bill.fetchone()
        values=[]
        while row is not None:
            zone_id,minute,value = row
            values.append("('%s:00',%d,%d,%d)"%(minute,zone_id,monitor_type,value))
            row = cursor_bill.fetchone()
        values=','.join(values)

        insert_sql = "insert into dmz_gm.monitordata (StatTime,ZoneID,MonitorType,MonitorData) values "+values
        try:
            insert_rows=cursor_web.execute(insert_sql)
        except Exception,data:
            logging.log(logging.ERROR,type+' '+data)
            sys.exit(0)
        logging.log(logging.INFO,type+' insert_rows: '+str(insert_rows))

        dt+=one_day

    conn_web.commit()
    cursor_web.close()
    cursor_bill.close()
    conn_web.close()
    conn_bill.close()

if __name__ != "__main__":
    types=('create_role','login','consume','recharge','wedding')
    def arg_exit(tip=''):
        sys.exit(tip+('\nusage:\n\tpython %s %s [%s] [Y-m-d H] [Y-m-d H]'%(sys.argv[0],sys.argv[1],'|'.join(types))))

    argc=len(sys.argv)
    if argc==3 or argc==5 or argc==7:
        if sys.argv[2] not in types:
            arg_exit('unknow type argument:'+sys.argv[2])

        if argc==3:
            datetime1=datetime.datetime.now()-datetime.timedelta(seconds=3600)
            datetime2=datetime1
        else:
            try:
                datetime1=datetime.datetime(*time.strptime(sys.argv[3]+' '+sys.argv[4],'%Y-%m-%d %H')[0:4])
                if argc==5:
                    datetime2=datetime1
                else:
                    datetime2=datetime.datetime(*time.strptime(sys.argv[5]+' '+sys.argv[6],'%Y-%m-%d %H')[0:4])
            except ValueError,msg:
                arg_exit(str(msg))
    else:
        arg_exit('argument count error')

    dmz_minute(sys.argv[2],datetime1,datetime2)



